const assign = require('object-assign');
const querystring = require('querystring');


(function () {
    if (!Date.prototype.getRTime) {
        Date.prototype.getRTime = function () {
            let EndTime = this; //截止时间 前端路上 http://www.51xuediannao.com/qd63/
            let NowTime = new Date();
            /*var localTime = NowTime.getTime();
             var localOffset = NowTime.getTimezoneOffset() * 60000;
             var utc = localTime - localOffset;
             var offset = 8;
             var bombay = utc + (3600000*offset);
             var newNowTime = new Date(bombay);*/

            let t = EndTime.getTime() - NowTime.getTime();

            let d = Math.floor(t / 1000 / 60 / 60 / 24);
            let h = Math.floor(t / 1000 / 60 / 60 % 24);
            let m = Math.floor(t / 1000 / 60 % 60);
            let s = Math.floor(t / 1000 % 60);

            //getTimezoneOffset()
            return {
                '天': d,
                '小时': h,
                '分': m
            };
        };
    }
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (str) {
            return (this.match("^" + str) == str);
        };
    }
    if (!String.prototype.endsWith) {
        String.prototype.endsWith = function (str) {
            return (this.match(str + "$") == str);
        };
    }
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            // 用正则表达式将前后空格
            // 用空字符串替代
            return this.replace(/(^\s*)|(\s*$)/g, "");
        };
    }
    if (!String.prototype.splice) {
        String.prototype.splice = function (start, delCount, newSubStr) {
            return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
        };
    }
    if (!String.prototype.format) {
        String.prototype.format = function (args) {
            let result = this;
            if (arguments.length > 0) {
                if (arguments.length == 1 && typeof (args) == "object") {
                    for (let key in args) {
                        if (args[key] != undefined) {
                            let reg = new RegExp("({" + key + "})", "g");
                            result = result.replace(reg, args[key]);
                        }
                    }
                }
                else {
                    for (let i = 0; i < arguments.length; i++) {
                        if (arguments[i] != undefined) {
                            let reg = new RegExp("({)" + i + "(})", "g");
                            result = result.replace(reg, arguments[i]);
                        }
                    }
                }
            }
            return result;
        };
    }
})();
const lyby = {
    /**
     * 根据图片url获取 指定大小
     * @param url
     * @param p
     * @returns {string}
     */
    getPImgUrlByUrl: function (url = '', p = 'p6') {
        let res = '';
        if (url) {
            if (url.split('!').length > 1) {
                res = url.split('!')[0] + '!' + p;
            } else {
                res = url;
            }
        }
        return res;
    },
    addCookie: function (name, value, expiresHours, cookiesForAll) {
        let cookieString = name + "=" + escape(value);
        //判断是否设置过期时间,0代表关闭浏览器时失效
        if (expiresHours > 0) {
            let date = new Date();
            date.setTime(date.getTime() + expiresHours * 1000);
            cookiesForAll == true ? (cookieString = cookieString + ";expires=" + date.toUTCString() + ";path=/;") : (cookieString = cookieString + ";expires=" + date.toUTCString());
        }
        document.cookie = cookieString;
    },
    editCookie: function (name, value, expiresHours, cookiesForAll) {
        let cookieString = name + "=" + escape(value);
        if (expiresHours > 0) {
            let date = new Date();
            date.setTime(date.getTime() + expiresHours * 1000); //单位是毫秒
            cookiesForAll == true ? (cookieString = cookieString + ";expires=" + date.toGMTString() + ";path=/;") : (cookieString = cookieString + ";expires=" + date.toGMTString());
        }
        document.cookie = cookieString;
    },
    //根据名字获取cookie的值
    getCookieValue: function (name) {
        let strCookie = document.cookie;
        let arrCookie = strCookie.split("; ");
        for (let i = 0; i < arrCookie.length; i++) {
            let arr = arrCookie[i].split("=");
            if (arr[0] == name) {
                return unescape(arr[1]);
            }
        }
        return 0;
    },
    localStorage: {
        setValue: function (key, value) {
            if (typeof(localStorage) != 'undefined') {
                localStorage[key] = value;
            }
        },
        getValue: function (key) {
            if (typeof(localStorage) != 'undefined') {
                return localStorage[key];
            }
            return '';
        }
    },
    superObj: {
        _onChange: function () {
            this.setState(this.state.getData());
        },
        componentDidMount: function () {
            this.state.on(this._onChange);
            if (this.state.init instanceof Function) {
                this.state.init();
            }
        },
        componentWillUnmount: function () {
            this.state.remove(this._onChange);
        }
    },
    loginUser: function () {
        let data = typeof(window.VCG) != 'undefined' ? window.VCG : {};
        return {
            getData: function () {
                return data;
            }
        };
    }(),
    validateUser: function () {
        let d = this.loginUser.getData();
        if (d.id || d.userId) {
            return true;
        } else {
            location.href = '/user/login?redirect=' + encodeURIComponent(location.href);
            return false;
        }
    },
    arrayContains: function (array, value) {
        return (Array.prototype.includes ? array.includes(value) : array.some(el => el === value));
    },
    shareConfig: function (options) {
        let title = options.title;
        if (typeof(document) != 'undefined') {
            if (title) {
                document.title = title;
            }
            if (options.imgUrl) {
                $(document.body).prepend(['<img src="', options.imgUrl, '" style="position: absolute;display: block;top:-1000px;left:-1000px;width:0;height:0;" />'].join(''));
            }
        }
    },
    lang: {
        upload: {}
    },
    /**
     * 将参数对象转换为，url参数字符串： {a: 1,b: 2} -> 'a=1&b=2'
     * @param paramsObj
     * @returns {string}
     */
    getQueryStrFromObj: function (paramsObj) {
        let _resStr = '';
        if (typeof paramsObj == 'object') {
            for (let p in paramsObj) {
                _resStr += p + '=' + paramsObj[p] + '&';
            }
        }
        //去掉最后一个&
        return _resStr.substring(0, _resStr.length - 1);
    },
    errorMsg: function () {
    },
    isEmptyObj: function (obj) {
        for (let i in obj) {
            return false;
        }
        return true;
    },
    htmlencode: function (s) {
        let div = document.createElement('div');
        div.appendChild(document.createTextNode(s));
        return div.innerHTML;
    },
    htmldecode: function (s) {
        if (!s)
            return '';
        let div = document.createElement('div');
        div.innerHTML = s;
        return div.innerText || div.textContent;
    },
    escape2Html: function (str) {
        let arrEntities = {'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"'};
        return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
            return arrEntities[t];
        });
    },
    percentage: function (numOrstr) {
        if (!numOrstr) {
            numOrstr = 0;
        }
        return parseFloat((parseFloat(numOrstr) * 100).toPrecision(12)) + '%';
    },
    getOS: function () {
        if (navigator.userAgent.indexOf('Window') > 0) {
            return 'windows';
        } else if (navigator.userAgent.indexOf('Mac OS X') > 0) {
            return 'mac';
        } else if (navigator.userAgent.indexOf('Linux') > 0) {
            return 'linux';
        } else {
            return '';
        }
    },
    ismobile: function () {
        if (typeof window.navigator != 'undefined') {
            return window.navigator.userAgent.match(/Android/i) || window.navigator.userAgent.match(/iPhone|iPod/i) ? !0 : !1;
        }
        return false;
    }(),
    isIPhone: function () {
        if (typeof navigator != 'undefined') {
            return /(iPhone|iPad|iPod)/i.test(navigator.userAgent);
        }
        return false;
    }(),
    isAndroid: function () {
        if (typeof navigator != 'undefined') {
            return /(Android)/i.test(navigator.userAgent);
        }
        return false;
    }(),
    isTouch: function () {
        if (typeof navigator != 'undefined') {
            return navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone|iPod|iPad/i) ? !0 : !1;
        }
        return false;
    }(),
    stringify: function (jsonObj) {
        return encodeURI(JSON.stringify(jsonObj));
    },
    domain : 'http://node.zenchina.org',
    ajax: function (options) {
        return $.ajax(assign(options, {
            headers: {
                'requestSource': 'shijue'
            }
        }));
    },
    zhanweituUrl: '//cdn.500px.me/images/qianyue/zhanweitu.png?dc=1',
    defaultImgUrl: '',
    default_avatar: 'https://500px.me/images/default_tx.png',
    default_avatar_cdn: '//pic.500px.me/images/default_tx.png',
    user_avatar: function (obj) {
        let avatarUrl;
        if (obj && obj.avatar) {
            if (typeof obj.avatar == 'string') {
                try {
                    obj.avatar = JSON.parse(obj.avatar);
                } catch (e) {
                    return avatarUrl || this.default_avatar;
                }
            }
            avatarUrl = obj.avatar['a2'] || obj.avatar['a1'];// || avatarUrl;
            if (!avatarUrl && obj.avatar.baseUrl) {
                if (obj.avatar.baseUrl.match(/^(https|http):\/\/(c\.shijue\.me|img\.500px\.me)/)) {
                    avatarUrl = obj.avatar.baseUrl + '!a1';
                } else {
                    avatarUrl = obj.avatar.baseUrl;
                }
            }
        }
        return avatarUrl || this.default_avatar;
    },
    transDate: function (curTime) {
        let date = curTime;
        let tt = new Date(parseInt(date));
        let days = parseInt((new Date().getTime() - date) / 86400000);

        // console.log('new Date().getTime() ', new Date().getTime());
        // console.log('date: ', date);
        // console.log('(new Date().getTime() - date)', (new Date().getTime() - date));

        let today = new Date().getDate();
        let year = tt.getFullYear();
        let mouth = tt.getMonth() + 1;
        let day = tt.getDate();
        let time = tt.getHours() < 10 ? "0" + tt.getHours() : tt.getHours();
        let min = tt.getMinutes() < 10 ? "0" + tt.getMinutes() : tt.getMinutes();
        let result, offset;
        offset = Math.abs(today - day);

        // console.log('days', days);
        // console.log('offset', offset);

        if (days < 4 && offset < 3) {
            if (offset === 0) {
                result = "今天 " + time + ":" + min;
            } else if (offset === 1) {
                result = "昨天 " + time + ":" + min;
            } else if (offset === 2) {
                result = "前天 " + time + ":" + min;
            }
        } else {
            result = year + "-" + mouth + "-" + day + " " + time + ":" + min;
        }

        return result;
    },
    imgLoadError: function (evt) {
        evt.target.src = lyby.default_avatar;
    },
    /*paramstr是阿里对图片进行处理的参数*/
    getImgUrl: function (opt, paramstr) {
        let url = '';
        /*if (paramstr) {
         paramstr+='_1o';
         }else{
         paramstr = '';
         }*/
        paramstr = paramstr || '';
        if (opt && opt.url) {
            try {
                let urlFlag = 'p2';
                if (typeof opt.url == 'string') {
                    opt.url = JSON.parse(opt.url);
                }
                let wNum = paramstr.match(/^@(\d+)w_.*/);
                if (wNum) {
                    let nw = parseInt(wNum[1]);
                    if (nw > 2000) {
                        urlFlag = 'p5';
                    } else if (nw < 600) {
                        urlFlag = 'p1';
                    } else if (nw == 900) {
                        urlFlag = 'p3';
                    }
                }
                let hNum = paramstr.match(/^@(\d+)h_.*/);
                if (hNum) {
                    let hw = parseInt(hNum[1]);
                    if (hw == 600) {
                        urlFlag = 'p3';
                    }
                }

                if (paramstr === 'p3') {
                    urlFlag = paramstr;
                } else if (paramstr === 'p6') {
                    urlFlag = paramstr;
                } else if (lyby.ismobile) {
                    //mobile 变小
                    if (urlFlag == 'p5') {
                        urlFlag = 'p3';
                    } else {
                        urlFlag = 'p1';
                    }
                }
                url = opt.url[urlFlag] || '';
            } catch (e) {
                console.log(e);
            }
        }
        //return (url+paramstr);
        return url;//url.replace('.jpg','');
    },
    default_coverUrl: 'https://cdn.shijue.me/images/basic-01.jpg',
    user_coverUrl: function (obj) {
        let coverUrls = this.default_coverUrl;
        if (obj && obj.coverUrl) {
            if (typeof obj.coverUrl == 'string') {
                coverUrls = obj.coverUrl || coverUrls;//JSON.parse(obj.avatar)
            } else {
                coverUrls = obj.coverUrl['p6'] || coverUrls;
            }
        }
        return coverUrls;
    },
    getUserDetailLink: function (userinfo) {
        let userDetailStr = ''; //'/community/user-details/' + userinfo.id;
        if (userinfo.userName) {
            userDetailStr = '/' + userinfo.userName;
        } else {
            userDetailStr = '/community/user-details/' + userinfo.id;
        }
        return userDetailStr;
    },
    validLink: function (linkStr) {
        let reg = /(http:\/\/|https:\/\/)(((\w|-)+\.(\w|-)+)+((\w|=|\?|\.|\/|&|-)*))/g;
        return reg.test(linkStr);
    },
    get4BytesCharacter: function (strParam) {
        let str = strParam || "";
        let result = [];

        for (let c of str) {
            if (c.codePointAt(0) > 0xFFFF) {
                result.push(c);
            }
        }
        return result;
    }
};
module.exports = lyby;